package com.infotech.NginxMonitor.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MemInfo {
	private static int memTotal; // KB
	private static int memFree;
	private static int swapTotal;
	private static int swapFree;

	public void refresh() {
		String str;

		BufferedReader reader;
		try {
			reader = new BufferedReader(new FileReader(
					new File("/proc/meminfo")));
			Pattern pattern = Pattern.compile("(\\w+):\\s+(\\d+)");
			HashMap<String, Integer> hashmap = new HashMap<String, Integer>();
			while ((str = reader.readLine()) != null) {
				Matcher matcher = pattern.matcher(str);
				if (matcher.find()) {
					hashmap.put(matcher.group(1),
							Integer.parseInt(matcher.group(2)));
				}
			}
			reader.close();
			MemInfo.memTotal = hashmap.get("MemTotal");
			MemInfo.memFree = hashmap.get("MemFree");
			MemInfo.swapTotal = hashmap.get("SwapTotal");
			MemInfo.swapFree = hashmap.get("SwapFree");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public int getMemTotal() {
		return MemInfo.memTotal;
	}

	public int getMemFree() {
		return MemInfo.memFree;
	}

	public int getSwapTotal() {
		return MemInfo.swapTotal;
	}

	public int getSwapFree() {
		return MemInfo.swapFree;
	}

}
